<!-- 职务列表-新增职务 -->
<template>
  <a-modal
    width="60%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
    unmount-on-close
  >
    <template #title>
      {{ type === 1 ? '新增职务' : '职务详情' }}
    </template>
    <div>
      <!-- <a-button
        :style="{
          float: 'right',
          marginBottom: '20px'
        }"
        type="primary"
        @click="edit"
        v-if="type === 2"
        >点击编辑</a-button
      > -->
      <a-form :model="formData" auto-label-width :rules="rules" ref="refForm">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="职务名称：" field="name">
              <a-input
                v-model="formData.name"
                placeholder="请输入"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="职务编号：" field="postNum">
              <a-input
                v-model="formData.postNum"
                placeholder="系统自动生成"
                allow-clear
                disabled
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="职务类别：" field="postType">
              <a-select
                v-model="formData.postType"
                ref="countryRef"
                placeholder="请选择"
                allow-search
                allow-clear
              >
                <a-option
                  v-for="item in typeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="职务级别：" field="postLevel">
              <a-select
                v-model="formData.postLevel"
                ref="countryRef"
                placeholder="请选择"
                allow-search
                allow-clear
              >
                <a-option
                  v-for="item in levelList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.postLevelName"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生效日期：" field="postTime">
              <a-date-picker
                v-model="formData.postTime"
                placeholder="请输入"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="启用状态：" field="postStatus">
              <a-switch
                :checked-value="1"
                :unchecked-value="2"
                v-model="formData.postStatus"
              ></a-switch>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-item label="职务权限：">
              <a-textarea
                v-model="formData.postAuthority"
                show-word-limit
                :max-length="800"
                :auto-size="{
                  minRows: 5
                }"
                allow-clear
                placeholder="请输入"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="职务职责：">
              <a-textarea
                v-model="formData.postDuty"
                show-word-limit
                :max-length="800"
                :auto-size="{
                  minRows: 5
                }"
                allow-clear
                placeholder="请输入"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-item label="备注说明：">
              <a-textarea
                v-model="formData.remark"
                show-word-limit
                :max-length="800"
                :auto-size="{
                  minRows: 5
                }"
                allow-clear
                placeholder="请输入"
              ></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  GetJobTypeList,
  GetJobLevelList
} from '@/apis/management/organization/baseSetting';
import { CheckJobList } from '@/apis/management/organization/positionManagement';
import { validateRules } from '@/utils/common';
import { cloneDeep } from 'lodash';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    list?: any; // 传进来的数据
    type: number; // 1 新增 2编辑详情
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'jobAddEmit']);
// 校验名字查重
const validateName = async (val: string, cb: any) => {
  try {
    if (val === props.list?.name && formData.value.id) {
      //
    } else {
      const data = {
        name: val
      };
      const res = await validateRules(CheckJobList, data);
      if (res.code) {
        cb(`${res.msg}`);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 校验编码查重
const validateNums = async (val: string, cb: any) => {
  try {
    if (val === props.list?.postNum && formData.value.id) {
      //
    } else {
      const data = {
        postNum: val
      };
      const res = await validateRules(CheckJobList, data);
      if (res.code) {
        cb(`${res.data}`);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  // postNum: [
  //   {
  //     required: true,
  //     message: '请输入'
  //   },
  //   {
  //     validator: validateNums
  //   }
  // ],
  postType: [
    {
      required: true,
      message: '请选择'
    }
  ],
  postLevel: [
    {
      required: true,
      message: '请选择'
    }
  ],
  postTime: [
    {
      required: true,
      message: '请选择'
    }
  ],
  postStatus: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

const formData = ref({
  name: '', // 职务名称
  postNum: '', // 职务编号
  postType: undefined, // 职务类别
  postLevel: undefined, // 职务等级
  postTime: '', // 生效时间
  postStatus: 1, // 职务状态 1: 启用 2: 不启用
  remark: '', // 备注
  postAuthority: '', // 职务权限
  postDuty: '' // 职务职责
});

const typeList = ref<any>({}); // 储存职务类别数据
const levelList = ref<any>([]); // 储存职务级别数据

// 获取组织类型数据
const getData = async () => {
  try {
    const res: any = await Promise.all([
      GetJobTypeList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetJobLevelList({
        pageNumber: 0,
        pageSize: -1
      })
    ]);
    typeList.value = res[0].content.filter((el: any) => el.enable === 1);
    levelList.value = res[1].content.filter((el: any) => el.status === 1);
  } catch (error: unknown) {
    console.log(error);
  }
};

let isEdit = ref(false); // 判断是否点击了编辑按钮
const edit = () => {
  isEdit.value = !isEdit.value;
};

let refForm = ref();
// 保存
const handleOk = async () => {
  if (await refForm.value.validate()) {
    return;
  } else {
    emit('jobAddEmit', formData.value);
    formData.value = {
      name: '', // 职务名称
      postNum: '', // 职务编号
      postType: undefined, // 职务类别
      postLevel: undefined, // 职务等级
      postTime: '', // 生效时间
      postStatus: 1, // 职务状态 1: 启用 2: 不启用
      remark: '', // 备注
      postAuthority: '', // 职务权限
      postDuty: '' // 职务职责
    };
  }
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  formData.value = {
    name: '', // 职务名称
    postNum: '', // 职务编号
    postType: undefined, // 职务类别
    postLevel: undefined, // 职务等级
    postTime: '', // 生效时间
    postStatus: 1, // 职务状态 1: 启用 2: 不启用
    remark: '', // 备注
    postAuthority: '', // 职务权限
    postDuty: '' // 职务职责
  };
};

watch(
  () => props.visible,
  (newVal: boolean, oldVal: boolean) => {
    if (newVal) {
      getData();
      if (props.list.id) formData.value = cloneDeep(props.list);
    }
  }
);
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
